# -*- coding: UTF-8 -*-
from flask import Flask, request
from flask_restful import Resource, Api,reqparse
from model.configner import ConfigNer
from model.ner_model import NERModel
from ner import Ner_recognition
import os
import sys
pwd = os.getcwd()
sys.path.append(pwd)
app = Flask(__name__)
app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))
api = Api(app)
os.environ["CUDA_VISIBLE_DEVICES"] = "0"

#curl http://10.11.255.23:5000/get/ner_result/ -d 'data_string=本所律师同意将本法律意见书随贵公司本次会议决议一起予以公告' -X POST

"""
class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data_string']
        #result_string=product_file(ner,todos[todo_id],model)
        result_string = product_str(ner, todos[todo_id], model)
        return result_string
"""
parser = reqparse.RequestParser()
parser.add_argument('string', type=str, required=True)
print 22222
config = ConfigNer()
model = NERModel(config)
model.build()
model.restore_session(config.dir_model)
ner = Ner_recognition()
print 1111
def get_file_name(data_root_path,file_type):
    file_name=[]
    for root ,dir, files in os.walk(data_root_path):
        for file in files :
            if file_type in file :
                file_name.append(file)
    return file_name


def Alignment_result(word_entity):
    word=[]
    entity=[]
    for i,token in enumerate(word_entity):
        word.append(word_entity[i][0])
        entity.append(word_entity[i][-1])
    return word,entity
def get_token(words, tag_result):
    insert_words =""
    word_list = []
    insert_tags = []
    word_entity_result = []
    for i,tag in enumerate(tag_result):
        if tag == 'O':
            continue
        elif i <= len(tag_result) - 2:
            tag_list = tag.split('-')
            if tag_list[0]=='B' and tag_result[i+1].split('-')[0]=='B':
                word_list.append(words[i])
                insert_tags.append(tag_list[1])
            elif tag_list[0]=='I' and (tag_result[i+1].split('-')[0]=='B' or tag_result[i+1].split('-')[0]=='O'):
                insert_words = insert_words + words[i]
                word_list.append(insert_words)
                insert_tags.append(tag_list[1])
                insert_words=""
            else:
                insert_words=insert_words+words[i]
        else:
            tag_list = tag.split('-')
            insert_words = insert_words + words[i]
            word_list.append(insert_words)
            insert_tags.append(tag_list[1])
            insert_words = ""
    assert len(word_list)==len(insert_tags)
    for w, t in zip(word_list, insert_tags):
        word_entity_result.append("/".join([w, t]))
    return word_entity_result

def product_str(ner, str, model):
    if str != "":
        tag_result = ner.ner_model(model=model, senceten=str)
        # print tags_result
        words,entity = Alignment_result(tag_result)
        tag_result=ner.check_ner(entity)
        result = get_token(words, tag_result)
    else:
        result=""
    return result

class Ner_api(Resource):

    def post(self):
        str=request.form['data_string']
        result_string = product_str(ner,str, model)
        return result_string





api.add_resource(Ner_api, '/get/ner_result/')

if __name__ == '__main__':
    app.run(host='10.11.255.23',debug=True)

